import type { UploadFiles } from 'element-plus'
import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import type {
  AssetLampPostImportProps,
  AssetLampPostImportState,
  AssetLampPostImportErrorDataItem
} from './typings'
import { defineComponent, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElLink,
  ElInput,
  ElButton,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import BaseUpload from '~/components/ProForm/BaseUpload'
import ProSaasTable from '~/components/ProSaasTable'
import { MODAL_SMALL_WIDTH, MODAL_NORMAL_WIDTH } from '~/utils/const'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'AssetLampPostImportModal',
  props: ['doCancel'],
  setup(props: AssetLampPostImportProps) {
    const stroe = useStore()

    const state = reactive<AssetLampPostImportState>({
      loading: false,
      errorVisible: false,
      errorData: {},
      fileList: []
    })

    const handleChangeFileList = (_: unknown, uploadFiles: UploadFiles) => {
      state.fileList = uploadFiles
    }

    const handleImportFile = async () => {
      if (!state.fileList?.length) {
        ElMessage.warning('请上传文件')
        return
      }
      state.loading = true
      const formData = new FormData()
      formData.append('file', state.fileList?.[state.fileList?.length - 1]?.raw as Blob)

      const res = await stroe.dispatch('assetLampPost/ImportAssetLampPostExcel', formData)

      state.loading = false
      if (!res?.success) return

      if (res?.data?.isSuccess) {
        props?.doCancel?.()
        ElMessageBox({
          title: '数据导入',
          message: (
            <section>
              <p class={styles['success-import-title']}>
                <ElLink underline={false} type="success" icon={CircleCheckFilled} />
                &nbsp;导入成功
              </p>
              <p class={styles['success-import-content']}>
                本次批量导入数据&nbsp;
                <ElLink underline={false} type="primary">
                  {res?.data?.count ?? 0}
                </ElLink>
              </p>
            </section>
          ),
          confirmButtonText: '确认',
          closeOnClickModal: false, // 点遮罩层不关弹窗
          draggable: true // 可拖拽
        })
      } else {
        state.errorVisible = true
        state.errorData = res?.data || {}
      }
    }

    // 失败时的返回数据展示用的表头配置
    const columns: TableColumnProps<AssetLampPostImportErrorDataItem>[] = [
      {
        label: '名称',
        prop: 'number',
        showOverflowTooltip: true,
        minWidth: 180,
        align: 'center'
      },
      {
        label: '状态',
        prop: 'errorMessage',
        showOverflowTooltip: true,
        minWidth: 180,
        align: 'center',
        render: (_, value) => (
          <>
            <ElLink underline={false} type="danger" icon={CircleCloseFilled} />
            &nbsp;{value}
          </>
        )
      }
    ]

    return () => (
      <ElDialog
        title="数据导入"
        modelValue={true}
        width={!state.errorVisible ? MODAL_SMALL_WIDTH : MODAL_NORMAL_WIDTH}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        beforeClose={props.doCancel}
        v-slots={
          !state.errorVisible && {
            footer: () => (
              <>
                <ElButton type="primary" loading={state.loading} onClick={handleImportFile}>
                  确定
                </ElButton>
                <ElButton onClick={props.doCancel}>取消</ElButton>
              </>
            )
          }
        }
      >
        {!state.errorVisible && (
          <ElDescriptions column={1} class={styles['import-upload-box']}>
            <ElDescriptionsItem label="批量导入表格模板">
              <ElLink
                type="primary"
                underline={false}
                href="/file/灯杆灯具数据导入模板.xlsx"
                {...{ download: '灯杆灯具数据导入模板' }}
              >
                点击下载表格
              </ElLink>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="批量导入文件选择">
              {/* 不使用默认上传自己封装 */}
              <BaseUpload
                accept=".xlsx,.xls"
                autoUpload={false}
                limit={1}
                onChange={handleChangeFileList}
                v-slots={{
                  tip: () => (
                    <section>
                      单次导入数据最多为
                      <ElLink type="primary" underline={false}>
                        1000条
                      </ElLink>
                    </section>
                  )
                }}
              >
                <ElInput readonly modelValue={state.fileList?.[state.fileList?.length - 1]?.name}>
                  {{
                    prefix: () => (
                      <ElLink type="primary" underline={false}>
                        <AliIcon type="icon-piliangdaoru" />
                      </ElLink>
                    )
                  }}
                </ElInput>
              </BaseUpload>
            </ElDescriptionsItem>
          </ElDescriptions>
        )}
        {state.errorVisible && (
          <>
            <section class={styles['error-import-header']}>
              <span class={styles['error-import-title']}>
                <ElLink underline={false} type="danger" icon={CircleCloseFilled} />
                &nbsp; 导入失败
              </span>
              <span class={styles['error-import-summary']}>
                共计&nbsp;
                <ElLink underline={false} type="danger">
                  {state.errorData?.errorMsg?.length ?? 0}
                </ElLink>
                &nbsp;条数据错误
              </span>
            </section>
            <ProSaasTable<AssetLampPostImportErrorDataItem>
              columns={columns}
              data={state.errorData.errorMsg || []}
              needPagination={false}
            />
          </>
        )}
      </ElDialog>
    )
  }
})
